<template>
   <div class="p-2">
   <div class="viewBox">
    <div class="p-2">
    <div class="viewBox">
      <el-form ref="testFormRef" :model="form" :rules="rules" label-width="120px">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本信息" name="information">
            <el-form-item label="实验名称" prop="testName">
              <el-input v-model="form.testName" placeholder="请输入实验名称" />
            </el-form-item>
            <el-form-item label="学科" prop="subject">
              <el-input v-model="form.subject" placeholder="请输入学科" />
            </el-form-item>
            <el-form-item label="年级" prop="grade">
              <el-input v-model="form.grade" placeholder="请输入年级" />
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="实验原理" name="principle">
            <el-form-item label="实验原理" prop="principle">
              <editor v-model="form.principle" :min-height="120" placeholder="请输入内容" />
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="实验步骤" name="step">
            <div v-for="(step, index) in formSteps" :key="index" class="step-item">
              <el-form-item :label="`步骤阶段 ${index + 1}`" :prop="`stepList.${index}.stage`">
                <el-input v-model="step.stage" placeholder="请输入步骤阶段" />
              </el-form-item>
              <el-form-item :label="`步骤名称 ${index + 1}`" :prop="`stepList.${index}.stepName`">
                <el-input v-model="step.stepName" placeholder="请输入步骤名称" />
              </el-form-item>
              <el-form-item :label="`步骤细节 ${index + 1}`" :prop="`stepList.${index}.detail`">
                <el-input v-model="step.detail" type="textarea" placeholder="请输入内容" />
              </el-form-item>
              <el-button type="danger" @click="removeStep(index)">删除步骤</el-button>
            </div>
            <el-button type="primary" @click="addStep">添加步骤</el-button>
          </el-tab-pane>
        </el-tabs>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-form>
    </div>
  </div>
   </div>
    
   
  </div>
</template>

<script setup name="Test" lang="ts">
import { listTest, getTest, delTest, addTest, updateTest } from '@/api/core/test';
// import { StepDetail,TestVO, TestQuery, TestForm } from '@/api/core/test/types';
import {  TestVO, TestQuery, TestForm } from '@/api/core/test/types';
const route = useRoute();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const activeTab = ref('information');
// const stepList = ref<StepDetail[]>([]);
const testList = ref<TestVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const testFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const formSteps = reactive<Array<{ stage: any; stepName: any; detail: any }>>([
  { stage: '', stepName: '', detail: '' }
]);

const formId = ref("");
const title = ref("");

const initFormData: TestForm = {
  id: undefined,
  testName: undefined,
  subject: undefined,
  grade: undefined,
  principle: undefined,
  stepList: []
}
const data = reactive<PageData<TestForm, TestQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    testName: undefined,
    subject: undefined,
    grade: undefined,
    principle: undefined,
    stepList: [],
    params: {
    }
  },
  rules: {
    testName: [
      { required: true, message: "实验名称不能为空", trigger: "blur" }
    ],
    subject: [
      { required: true, message: "学科不能为空", trigger: "blur" }
    ],
    grade: [
      { required: true, message: "年级不能为空", trigger: "blur" }
    ],
    principle: [
      { required: true, message: "实验原理不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);


/** 取消按钮 */
const cancel = () => {
  reset();
  proxy?.$router.go(-1);
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  testFormRef.value?.resetFields();
}


/** 提交按钮 */
const submitForm = () => {
  testFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        // 将 formSteps 的值复制到 form.stepList 中
        form.value.stepList = formSteps.map(step => ({
          stage: step.stage,
          stepName: step.stepName,
          detail: step.detail
        }));

        if (form.value.id) {
          await updateTest(form.value);
          ElMessage.success("修改成功");
        } else {
          await addTest(form.value);
          ElMessage.success("添加成功");
        
        }
        proxy?.$router.go(-1);
      } catch (error) {
        ElMessage.error("操作失败");
      } finally {
        buttonLoading.value = false;
      }
    }
  });
}

/** 添加步骤 */
const addStep = () => {
  formSteps.push({ stage: '', stepName: '', detail: '' });
}

/** 删除步骤 */
const removeStep = (index: number) => {
  formSteps.splice(index, 1);
}

/** 获取数据 */
/** 获取数据 */
(async () => {
  formId.value = route.query && (route.query.id as string);

  if (formId.value) {
    const res = await getTest(formId.value);
    Object.assign(form.value, res.data);
    // 正确地将后端返回的 stepList 赋值给 formSteps
    formSteps.length = 0; // 清空现有步骤
    res.data.stepList.forEach(step => {
      formSteps.push({ stage: step.stage, stepName: step.stepName, detail: step.detail });
    });
    title.value = "编辑";
  } else {
    title.value = "新增";
  }
})();
</script>
